import { Check, Copy, FileArchive, Pencil, Undo2, X } from "lucide-react";
import { useCallback, useEffect, useState } from "react";
import { useShallow } from "zustand/react/shallow";

import { ScrollContainer } from "~/components/deer-flow/scroll-container";
import { Tooltip } from "~/components/deer-flow/tooltip";
import { Button } from "~/components/ui/button";
import { Card } from "~/components/ui/card";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "~/components/ui/tabs";
import { useReplay } from "~/core/replay";
import { InterviewStore } from "~/core/store";
import { cn } from "~/lib/utils";

import { InterviewActivitiesBlock } from "./interview-activities-block";
import { InterviewEvaluatorBlock } from "./interview-evaluator-block";
import { InterviewReportBlock } from "./interview-report-block";
import { JdGeneratorBlock } from "./jd-generator-block";
import { QuestionGeneratorBlock } from "./question-generator-block";
import { ResumeMatcherBlock } from "./resume-matcher-block";
import { TalentPoolDrawer } from "./talent-pool-drawer";

type TabType =
  | "analysis"
  | "jd_generator"
  | "resume_matcher"
  | "question_generator"
  | "interview_evaluator";

type AnalysisTabType = "activities" | "report";

export function InterviewBlock({ className }: { className?: string }) {
  const [activeTab, setActiveTab] = useState<TabType>("analysis");
  const [activeAnalysisTab, setActiveAnalysisTab] =
    useState<AnalysisTabType>("activities");

  const reportId = InterviewStore.useLatestMessageId("reporter");
  const hasReport = reportId !== null;
  const reportStreaming = InterviewStore.useStore(
    useShallow((state) => reportId === state.ongoingMessageId),
  );

  const jdGeneratorId = InterviewStore.useLatestMessageId("jd_generator");
  const hasJdGeneratorId = jdGeneratorId !== null;
  const jdGeneratorStreaming = InterviewStore.useStore(
    useShallow((state) => jdGeneratorId === state.ongoingMessageId),
  );

  const resumeMatcherId = InterviewStore.useStore(
    useShallow((state) => state.lastResumeMatcherKeyMessageId),
  );
  const hasResumeMatcher = resumeMatcherId !== null;
  const resumeMatcherStreaming = InterviewStore.useStore(
    useShallow(
      (state) =>
        state.lastResumeMatcherKeyMessageId !== null &&
        state.ongoingMessageId !== null &&
        state.resumeMatcherMessageIds
          .get(state.lastResumeMatcherKeyMessageId)
          ?.includes(state.ongoingMessageId),
    ),
  );

  const questionGeneratorId = InterviewStore.useStore(
    useShallow((state) => state.lastQuestionGeneratorKeyMessageId),
  );
  const hasQuestionGenerator = questionGeneratorId !== null;
  const questionGeneratorStreaming = InterviewStore.useStore(
    useShallow(
      (state) =>
        state.lastQuestionGeneratorKeyMessageId !== null &&
        state.ongoingMessageId !== null &&
        state.questionGeneratorMessageIds
          .get(state.lastQuestionGeneratorKeyMessageId)
          ?.includes(state.ongoingMessageId),
    ),
  );

  const interviewEvaluatorId = InterviewStore.useStore(
    useShallow((state) => state.lastInterviewEvaluatorKeyMessageId),
  );
  const hasInterviewEvaluator = interviewEvaluatorId !== null;
  const interviewEvaluatorStreaming = InterviewStore.useStore(
    useShallow(
      (state) =>
        state.lastInterviewEvaluatorKeyMessageId !== null &&
        state.ongoingMessageId !== null &&
        state.interviewEvaluatorMessageIds
          .get(state.lastInterviewEvaluatorKeyMessageId)
          ?.includes(state.ongoingMessageId),
    ),
  );

  useEffect(() => {
    if (hasInterviewEvaluator) {
      setActiveTab("interview_evaluator");
    } else if (hasQuestionGenerator) {
      setActiveTab("question_generator");
    } else if (hasResumeMatcher) {
      setActiveTab("resume_matcher");
    } else if (hasJdGeneratorId) {
      setActiveTab("jd_generator");
    } else if (hasReport) {
      setActiveTab("analysis");
      setActiveAnalysisTab("report");
    }
  }, [
    hasReport,
    hasJdGeneratorId,
    hasResumeMatcher,
    hasQuestionGenerator,
    hasInterviewEvaluator,
  ]);

  const { isReplay } = useReplay();
  const [editing, setEditing] = useState(false);
  const [copied, setCopied] = useState(false);
  const handleCopy = useCallback(() => {
    if (!reportId) {
      return;
    }
    const report = InterviewStore.useStore.getState().messages.get(reportId);
    if (!report) {
      return;
    }
    void navigator.clipboard.writeText(report.content);
    setCopied(true);
    setTimeout(() => {
      setCopied(false);
    }, 1000);
  }, [reportId]);

  const handleEdit = useCallback(() => {
    setEditing((editing) => !editing);
  }, []);

  const talentPoolDrawerIsOpen = InterviewStore.useStore(
    useShallow((state) => state.talentPoolDrawerIsOpen),
  );

  const setTalentPoolDrawerOpen = (open: boolean) => {
    if (open) {
      InterviewStore.openTalentPoolDrawer();
    } else {
      InterviewStore.closeTalentPoolDrawer();
    }
  };

  return (
    <div className={cn("h-full w-full", className)}>
      <Card className={cn("relative h-full w-full pt-4", className)}>
        <div className="absolute right-4 flex h-9 items-center justify-center">
          {hasResumeMatcher && (
            <Tooltip title="人才库">
              <Button
                className="text-gray-400"
                size="sm"
                variant="ghost"
                onClick={() => {
                  InterviewStore.openTalentPoolDrawer();
                }}
              >
                <FileArchive />
              </Button>
            </Tooltip>
          )}
          <Tooltip title="关闭">
            <Button
              className="hidden text-gray-400"
              size="sm"
              variant="ghost"
              onClick={() => {
                InterviewStore.closeInterviewPanel();
              }}
            >
              <X />
            </Button>
          </Tooltip>
        </div>
        <Tabs
          className="flex h-full w-full flex-col"
          value={activeTab}
          onValueChange={(value) => setActiveTab(value as TabType)}
        >
          <div className="flex w-full justify-center">
            <TabsList className="">
              <TabsTrigger className="px-8" value="analysis">
                项目分析
              </TabsTrigger>
              <TabsTrigger
                className="px-8"
                value="jd_generator"
                disabled={!hasJdGeneratorId}
              >
                职位生成
              </TabsTrigger>
              <TabsTrigger
                className="px-8"
                value="resume_matcher"
                disabled={!hasResumeMatcher}
              >
                简历匹配
              </TabsTrigger>
              <TabsTrigger
                className="px-8"
                value="question_generator"
                disabled={!hasQuestionGenerator}
              >
                问题生成
              </TabsTrigger>
              <TabsTrigger
                className="px-8"
                value="interview_evaluator"
                disabled={!hasInterviewEvaluator}
              >
                面试评估
              </TabsTrigger>
            </TabsList>
          </div>
          <TabsContent
            className="h-full min-h-0 flex-grow px-8"
            value="analysis"
            forceMount
            hidden={activeTab !== "analysis"}
          >
            {hasReport && !reportStreaming && (
              <div className="absolute right-4 flex h-9 items-center justify-center">
                <Tooltip title="编辑报告">
                  <Button
                    className="text-gray-400"
                    size="icon"
                    variant="ghost"
                    disabled={isReplay}
                    onClick={handleEdit}
                  >
                    {editing ? <Undo2 /> : <Pencil />}
                  </Button>
                </Tooltip>
                <Tooltip title="复制">
                  <Button
                    className="text-gray-400"
                    size="icon"
                    variant="ghost"
                    onClick={handleCopy}
                  >
                    {copied ? <Check /> : <Copy />}
                  </Button>
                </Tooltip>
              </div>
            )}
            <Tabs
              className="flex h-full w-full flex-col"
              value={activeAnalysisTab}
              onValueChange={(value) =>
                setActiveAnalysisTab(value as AnalysisTabType)
              }
            >
              <div className="flex w-full justify-center">
                <TabsList className="">
                  <TabsTrigger
                    className="px-8"
                    value="report"
                    disabled={!hasReport}
                  >
                    报告
                  </TabsTrigger>
                  <TabsTrigger className="px-8" value="activities">
                    执行流程
                  </TabsTrigger>
                </TabsList>
              </div>
              <TabsContent
                className="h-full min-h-0 flex-grow px-8"
                value="report"
                forceMount
                hidden={activeAnalysisTab !== "report"}
              >
                <ScrollContainer
                  className="h-full px-5 pb-20"
                  scrollShadowColor="var(--card)"
                  autoScrollToBottom={!hasReport || reportStreaming}
                >
                  {reportId && (
                    <InterviewReportBlock
                      className="mt-4"
                      messageId={reportId}
                      editing={editing}
                    />
                  )}
                </ScrollContainer>
              </TabsContent>
              <TabsContent
                className="h-full min-h-0 flex-grow px-8"
                value="activities"
                forceMount
                hidden={activeAnalysisTab !== "activities"}
              >
                <ScrollContainer
                  className="h-full"
                  scrollShadowColor="var(--card)"
                  autoScrollToBottom={!hasReport || reportStreaming}
                >
                  <InterviewActivitiesBlock className="mt-4" />
                </ScrollContainer>
              </TabsContent>
            </Tabs>
          </TabsContent>
          <TabsContent
            className="h-full min-h-0 flex-grow px-8"
            value="jd_generator"
            forceMount
            hidden={activeTab !== "jd_generator"}
          >
            <ScrollContainer
              className="h-full px-5 pb-20"
              scrollShadowColor="var(--card)"
              autoScrollToBottom={!hasJdGeneratorId || jdGeneratorStreaming}
            >
              {jdGeneratorId && (
                <JdGeneratorBlock className="mt-4" messageId={jdGeneratorId} />
              )}
            </ScrollContainer>
          </TabsContent>
          <TabsContent
            className="h-full min-h-0 flex-grow px-8"
            value="resume_matcher"
            forceMount
            hidden={activeTab !== "resume_matcher"}
          >
            <ScrollContainer
              className="h-full px-5 pb-20"
              scrollShadowColor="var(--card)"
              autoScrollToBottom={!hasResumeMatcher || resumeMatcherStreaming}
            >
              {resumeMatcherId && (
                <ResumeMatcherBlock
                  className="mt-4"
                  messageId={resumeMatcherId}
                />
              )}
            </ScrollContainer>
          </TabsContent>
          <TabsContent
            className="h-full min-h-0 flex-grow px-8"
            value="question_generator"
            forceMount
            hidden={activeTab !== "question_generator"}
          >
            <ScrollContainer
              className="h-full px-5 pb-20"
              scrollShadowColor="var(--card)"
              autoScrollToBottom={
                !hasQuestionGenerator || questionGeneratorStreaming
              }
            >
              {questionGeneratorId && (
                <QuestionGeneratorBlock
                  className="mt-4"
                  messageId={questionGeneratorId}
                />
              )}
            </ScrollContainer>
          </TabsContent>
          <TabsContent
            className="h-full min-h-0 flex-grow px-8"
            value="interview_evaluator"
            forceMount
            hidden={activeTab !== "interview_evaluator"}
          >
            <ScrollContainer
              className="h-full px-5 pb-20"
              scrollShadowColor="var(--card)"
              autoScrollToBottom={
                !hasInterviewEvaluator || interviewEvaluatorStreaming
              }
            >
              {interviewEvaluatorId && (
                <InterviewEvaluatorBlock
                  className="mt-4"
                  messageId={interviewEvaluatorId}
                />
              )}
            </ScrollContainer>
          </TabsContent>
        </Tabs>
      </Card>
      <TalentPoolDrawer
        open={talentPoolDrawerIsOpen}
        setOpen={setTalentPoolDrawerOpen}
      />
    </div>
  );
}
